import router from "./router";
import store from "./store";
// import NProgress from "nprogress";
// import "nprogress/nprogress.css";
import getPageTitle from "@/utils/get-page-title";
import { Message } from "element-ui";
import { getToken } from "@/utils/auth"; // get token from cookie
import { queryUserList } from "@/api/user";

// NProgress.configure({ showSpinner: false });
const whiteList = ["/login"];
router.beforeEach(async (to, from, next) => {
  // 切换路由开启进度条
  // NProgress.start();
  // 设置页面title
  if (to.meta.title) {
    document.title = getPageTitle(to.meta.title);
  }
  const hasToken = getToken();
  if (hasToken) {
    queryUserList({
      page: 1,
      pageSize: 10,
      userName: localStorage.getItem("userName"),
    })
      .then((res) => {
        const { records } = res.data;
        if (Array.isArray(records) && records.length) {
          const { userName, roleId, phone } = records[0];
          store.dispatch(
            "permission/generateRoutes",
            {
              role: roleId,
              permission: "",
            },
            { root: true }
          );
          store.commit("user/SET_NAME", {
            userName,
            phone,
          });
        }
        if (to.path === "/login") {
          next({ path: "/" });
        } else {
          next();
        }
      })
      .catch(() => {});
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      next(`/login?redirect=${to.path}`);
    }
  }
});
router.afterEach(() => {
  // 进度条完成
  // NProgress.done();
});
